package com.lfs.market.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lfs.market.exception.ServiceException;
import com.lfs.market.mapper.ProductCollectMapper;
import com.lfs.market.model.R;
import com.lfs.market.model.entity.ProductCollect;
import com.lfs.market.model.enums.ResultCode;
import com.lfs.market.service.ProductCollectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ProductCollectServiceImpl extends ServiceImpl<ProductCollectMapper, ProductCollect> implements ProductCollectService {
    @Autowired
    private ProductCollectService productCollectService;

    /**
     * 取消收藏
     *
     * @param productId
     * @return
     */
    @Override
    public R delete(String productId) {
        ProductCollect collect = lambdaQuery().eq(ProductCollect::getUserId, StpUtil.getLoginIdAsString())
                .eq(ProductCollect::getProductId, productId).one();
        if (null == collect) throw new ServiceException(ResultCode.NotFindError);
        if (!collect.getUserId().equals(StpUtil.getLoginIdAsString()))
            throw new ServiceException(ResultCode.NotFindError);
        boolean remove = lambdaUpdate()
                .eq(ProductCollect::getUserId, StpUtil.getLoginIdAsString())
                .eq(ProductCollect::getProductId, productId).remove();
        if (!remove) throw new ServiceException(ResultCode.DeleteError);
        return R.ok();
    }

    /**
     * 收藏商品
     *
     * @param collect
     * @return
     */
    @Override
    public void collectProduct(ProductCollect collect) {
        ProductCollect one = productCollectService.lambdaQuery().eq(ProductCollect::getUserId, StpUtil.getLoginIdAsString())
                .eq(ProductCollect::getProductId, collect.getProductId()).one();
        if (!BeanUtil.isEmpty(one)) return;
        ProductCollect productCollect = new ProductCollect();
        productCollect.setUserId(StpUtil.getLoginIdAsString());
        productCollect.setProductId(collect.getProductId());
        productCollect.setCreateTime(new Date());
        productCollect.setUpdateTime(new Date());
        boolean save = productCollectService.save(productCollect);
        if (!save) throw new ServiceException(ResultCode.SaveError);
    }

    /**
     * 查询收藏列表
     *
     * @return
     */
    @Override
    public List<Object> getList() {
        String userId = StpUtil.getLoginIdAsString();
        List<ProductCollect> list = productCollectService.lambdaQuery().eq(ProductCollect::getUserId, userId).list();
        ArrayList<Object> objects = new ArrayList<>();
        list.forEach(collect -> {
            objects.add(collect.getProductId());
        });
        return objects;
    }
}
